﻿using Edu.Entitys;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Newtonsoft.Json;
using System.Collections.Generic;
using Volo.Abp;
using Volo.Abp.EntityFrameworkCore.Modeling;
using Volo.Abp.Users;

namespace Edu.EntityFrameworkCore
{
    public static class EduDbContextModelCreatingExtensions
    {
        public static void ConfigureEdu(this ModelBuilder builder)
        {
            Check.NotNull(builder, nameof(builder));

            /* Configure your own tables/entities inside here */
            builder.Entity<AppStudent>(b =>
            {
                b.ToTable(EduConsts.DbTablePrefix + "Students");

                b.Property<Dictionary<AbilityType, AbilityTypeLevel>>(nameof(AppStudent.Abilitys)).HasConversion(
                    d => JsonConvert.SerializeObject(d, Formatting.None),
                    s => JsonConvert.DeserializeObject<Dictionary<AbilityType, AbilityTypeLevel>>(s)
                ).HasColumnName(nameof(AppStudent.Abilitys));

                b.ConfigureByConvention();
            });

            builder.Entity<AppTeacher>(b =>
            {
                b.ToTable(EduConsts.DbTablePrefix + "Teachers");
                b.ConfigureByConvention();
            });

            builder.Entity<AppAchievement>(b =>
            {
                b.ToTable(EduConsts.DbTablePrefix + "Achievements");
                b.ConfigureByConvention();
            });

            builder.Entity<AppUserAchievement>(b =>
            {
                b.ToTable(EduConsts.DbTablePrefix + "UserAchievements");
                b.ConfigureByConvention();
            });

            builder.Entity<AppStudyTask>(b =>
            {
                b.ToTable(EduConsts.DbTablePrefix + "StudyTasks");

                b.Property<StudyTaskContent>(nameof(AppStudyTask.Content)).HasConversion(
                    d => JsonConvert.SerializeObject(d, Formatting.None),
                    s => JsonConvert.DeserializeObject<StudyTaskContent>(s)
                ).HasColumnName(nameof(AppStudyTask.Content));

                b.ConfigureByConvention();
            });

            builder.Entity<AppRating>(b =>
            {
                b.ToTable(EduConsts.DbTablePrefix + "Ratings");
                b.ConfigureByConvention();
            });
        }

        public static void ConfigureCustomUserProperties<TUser>(this EntityTypeBuilder<TUser> b)
            where TUser : class, IUser
        {
            b.Property<string>(nameof(AppUser.WeChatName)).HasMaxLength(128).HasDefaultValue("");
            b.Property<string>(nameof(AppUser.Area)).HasMaxLength(64).HasDefaultValue("");
            b.Property<string>(nameof(AppUser.Avatar)).HasMaxLength(256);
        }
    }
}